﻿using System;
using Newtonsoft.Json;

namespace EzDesk.Utility.Extensions
{
    public class EpochDateTimeConverter : JsonConverter
    {
        // Methods
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType != JsonToken.Integer)
            {
                throw new Exception(
                    string.Format("Unexpected token parsing date. Expected Integer, got {0}.", reader.TokenType.ToString())
                    );
            }

            var epoch = (long)reader.Value;
            var dateTime = EpochDateTimeExtension.FromEpoch(epoch);

            return dateTime;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (!(value is DateTime))
            {
                throw new Exception("Expected date object value.");
            }

            long epochValue = ((DateTime)value).ToEpoch();
            writer.WriteValue(epochValue);
        }

        public override bool CanConvert(Type objectType)
        {
            if ((objectType != typeof(DateTime)) && (objectType != typeof(DateTime?)))
            {
                return false;
            }
            return true;
        }

    }
}